#include <iostream>
#include <signal.h>

#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr=nullptr;

void Recovery(int signo)
{
    ctrl_ptr->ReonlineMachine();
}

int main()
{
    //signal(SIGINT,Recovery);
    // 创建服务器对象
    Server svr;
    //前端和后端交互功能
    Control control;
    //ctrl_ptr=&control;
    // 设置路由
    //获取题目列表
    svr.Get("/all_problems",[&control](const Request& req, Response& rsp)
    {
        std::string html;
        control.AllProblems(&html);
        // 返回题目列表
        rsp.set_content(html, "text/html;charset=utf-8");
    });

    //根据用户提交的题目编号，返回对应的题目
    // /problem/${题目编号}$
    svr.Get(R"(/problems/(\d+))", [&control](const Request& req, Response& rsp)
    {
       std::string id= req.matches[1];//获取正则表达式匹配到的内容
       std::string html;
       control.Problem(id,&html);
       //返回题目
       rsp.set_content(html, "text/html;charset=utf-8");
    });
    //用户提交判题请求
    //用户提交判题请求
    svr.Post(R"(/judge/(\d+))",[&control](const Request& req, Response& rsp)
    {   
        std::string id= req.matches[1];//获取正则表达式匹配到的内容
        std::string result_json;
        control.Judge(id,req.body,&result_json);
        //返回判题结果
        rsp.set_content(result_json, "application/json;charset=utf-8");
    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}